/*
 * @Date: 2024-04-11 14:47:55
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-04-13 13:35:39
 * @FilePath: \server\src\server\app\ChatRoomManager.cpp
 */
#include "ChatRoomManager.h"

#include "ChatRoom.h"
#include "mysql/MysqlUtils.h"

#include <data/UserInfo.pb.h>
#include <system/System.h>

ChatRoomManager::ChatRoomManager() {
    initChatRooms();
}

ChatRoomManager::~ChatRoomManager() {
}

ChatRoom::SharedPtr ChatRoomManager::getChatRoom(std::string roomId) {
    try {
        auto room = m_chatRooms.at(roomId);
        return room;
    }
    catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        return nullptr;
    }
}

ChatRoom::SharedPtr ChatRoomManager::createChatRoom(data::ChatRoomInfo& info) {
    if (MysqlUtils::createRoom(info)) {
        auto room   = boost::make_shared<ChatRoom>(info);
        auto status = m_chatRooms.insert({info.roomid(), room});
        if (status.second) {
            room->initConnect();
            return room;
        }
    }
    return nullptr;
}

void ChatRoomManager::sendMessage(data::Message msg) {
    auto room = getChatRoom(msg.to_user_id());
    if (room) {
        if (room->contains(msg.from_user_id()))
            room->deliver(msg);
    }
}

void ChatRoomManager::initChatRooms() {
    std::vector<data::ChatRoomInfo> infos;
    MysqlUtils::getRooms(infos);
    for (auto&& i : infos) {
        auto room = boost::make_shared<ChatRoom>(i);
        m_chatRooms.insert({i.roomid(), room});
        room->initConnect();
    }

    for (auto &&i : m_chatRooms)
    {
        std::cout << i.second->roomid() << ": " << i.second->info().DebugString()  << std::endl;
    }
    
}
